from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer
from rest_framework.views import APIView
from no_6.serializers.vip import CommonVideoSerializer, VIPVideoSerializer, SVIPVideoSerializer
from no_6.models import UserInfo, UserToken, CommonVideo, VIPVideo, SVIPVideo
from no_6.utils.auth import Authtication, VIP, SVIP


def md5(user):
    import hashlib
    import time
    ctime = str(time.time())
    m = hashlib.md5(bytes(user, encoding='utf-8'))
    m.update(bytes(ctime, encoding='utf-8'))
    return m.hexdigest()


# Create your views here.
class AuthView(APIView):
    """
    登录(目前账号：user1/pwd1、user2/pwd2、user3/pwd3)
    """

    authentication_classes = []
    permission_classes = []

    def post(self, request):
        ret = {'code': 1000, 'msg': '登录成功！'}
        try:
            # request.POST 在发JSON数据的时候是取不到值的，只有发urlecoding才会有值
            # REST已经对request再次封装了，发送JSON，urlecoding,form-data等常用等常用的数据都封装到data里了，这样就解决了request.POST 在发JSON数据的时候是取不到值的情况
            print("data", request.data)
            user = request.data.get('username')
            pwd = request.data.get('password')
            obj = UserInfo.objects.filter(username=user, password=pwd).first()
            if not obj:
                ret = {'code': 1001, 'msg': '用户名或密码错误'}
                return JsonResponse(ret)
            # 为登录用户创建token
            token = md5(user)
            print(token)
            # 存在则更新，不存在的创建
            UserToken.objects.update_or_create(user=obj, defaults={'token': token})
            ret['token'] = token
        except Exception as e:
            print('Exception', e)
            ret = {'code': 1002, 'msg': '请求异常'}
        return JsonResponse(ret)


class CommonVideoView(APIView):
    """
    登录后即可访问的内容资源
    """
    renderer_classes = [JSONRenderer]  # 渲染器
    authentication_classes = [Authtication, ]
    permission_classes = []

    def get(self, request):
        # print(request.user,request.auth)#user1 user1
        video_list = CommonVideo.objects.all()
        re = CommonVideoSerializer(video_list, many=True)
        return Response(re.data)


class VIPVideoView(APIView):
    """
    vip可访问的资源
    """
    renderer_classes = [JSONRenderer]  # 渲染器
    authentication_classes = [Authtication]
    permission_classes = [VIP]

    def get(self, request):
        video_list = VIPVideo.objects.all()
        re = VIPVideoSerializer(video_list, many=True)
        return Response(re.data)


class SVIPVideoView(APIView):
    """
    vip可访问的资源
    """
    renderer_classes = [JSONRenderer]  # 渲染器
    authentication_classes = [Authtication]
    permission_classes = [SVIP]

    def get(self, request):
        video_list = SVIPVideo.objects.all()
        re = SVIPVideoSerializer(video_list, many=True)
        return Response(re.data)
